package com.koomii.myproject.util;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class StablePDFCreate {
	
	/**
	 * 不太想花 时间 在 这上面 了 先拿这种决绝 方案吧， 呼呼 有时间 在 想更完美的方案。
	 */
/*	public static void main(String[] args)throws Exception {
		OutputStream out = new FileOutputStream(new File("stable2.pdf"));
		createPDF("f.html", out);
		out.close();

	}*/
	public static void  createPDF(String html,OutputStream out)throws Exception{
		ClassLoader loader = StablePDFCreate.class.getClassLoader();
		ITextRenderer renderer = new ITextRenderer();
		//renderer.setDocument(new File(html));
		renderer.setDocumentFromString(html);
//		ITextFontResolver resolver = renderer.getFontResolver();
//		resolver.addFont(loader.getResource("simsun.ttc").toString(), BaseFont.IDENTITY_H,     
//                BaseFont.NOT_EMBEDDED);  
		renderer.layout();
		ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
		renderer.createPDF(bufOut);

		PdfReader reader = new PdfReader(bufOut.toByteArray(), "PDF".getBytes());
        PdfStamper  stamper = new PdfStamper(reader,out);
        Image image =Image.getInstance(loader.getResource("HLD.png"));
        image.setAbsolutePosition(0, 0);
        
        for(int i=1;i<=reader.getNumberOfPages();i++){
        	PdfContentByte under = stamper.getUnderContent(i);
        	if(under!=null)under.addImage(image);
        }
        bufOut.close();
        stamper.close();
        reader.close();
	}
	
}
